package pers.flowerinsnow.minecraft.forge.shiftability.command

import net.minecraft.client.Minecraft
import net.minecraft.command.CommandBase
import net.minecraft.command.ICommandSender
import pers.flowerinsnow.minecraft.forge.shiftability.ShiftAbility
import pers.flowerinsnow.minecraft.forge.shiftability.listener.TickListener
import pers.flowerinsnow.minecraft.forge.shiftability.manager.ISAConfigManager
import java.lang.NumberFormatException
import java.util.*

class CommandShiftAbility : CommandBase() {
    override fun getCommandName(): String {
        return "shiftability"
    }

    override fun getCommandUsage(sender: ICommandSender?): String {
        return parseColor("&7[&a?&7]&a用法: &e/shiftability(sa) &b- 开启/关闭\n" +
                "&e/shiftability(sa) <循环时间> &b- 设置潜行每次间隔时间")
    }

    override fun processCommand(sender: ICommandSender, args: Array<out String>) {
        if (sender == Minecraft.getMinecraft().thePlayer) {
            if (args.isEmpty()) {
                val old = ISAConfigManager.ConfigEntry.GENERAL_ENABLE.get().boolean
                if (old) {
                    TickListener.next = -1L;
                    ShiftAbility.addChat("command.shiftability.disable")
                } else {
                    TickListener.next = System.currentTimeMillis() + ISAConfigManager.ConfigEntry.GENERAL_PERIOD.get().int
                    ShiftAbility.addChat("command.shiftability.enable")
                }
                ISAConfigManager.ConfigEntry.GENERAL_ENABLE.get().set(!old)
                ShiftAbility.configManager.save()
            } else if (args.size == 1) {
                try {
                    val arg = args.get(0).toInt()
                    ISAConfigManager.ConfigEntry.GENERAL_PERIOD.get().set(arg)
                    ShiftAbility.addChat("command.shiftability.success")
                    ShiftAbility.configManager.save()
                } catch (e : NumberFormatException) {
                    ShiftAbility.addChat("command.shiftability.invalidnumber")
                }
            } else ShiftAbility.addChat(getCommandUsage(sender))
        }
    }

    override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean {
        return sender == Minecraft.getMinecraft().thePlayer
    }

    override fun getCommandAliases(): MutableList<String> {
        return Collections.singletonList("sa")
    }
    fun parseColor(s : String) : String {
        return s.replace("&", "§").replace("§§", "&")
    }
}